package au.com.koalaclass.controller;

import au.com.koalaclass.config.GatewayServiceHandler;
import au.com.koalaclass.dao.GatewayRouteDao;
import au.com.koalaclass.entity.GatewayRouteEntity;
import au.com.koalaclass.entity.GatewayRouteRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Superlu
 * @version 1.0.0
 * @ClassName RouteController
 * @Description TODO
 * @createTime 2021/11/15 11:18
 */
@RestController
@RequestMapping("/router")
public class RouteController {

    @Resource
    private GatewayServiceHandler gatewayServiceHandler;

    @Resource
    private GatewayRouteDao gatewayDao;

    @GetMapping("/refresh")
    public String refresh() throws JsonProcessingException {
        return gatewayServiceHandler.loadRouteConfig();
    }
    @GetMapping("/findAll")
    public List<GatewayRouteEntity> findAll(){
        return gatewayDao.findAll();
    }

    @PostMapping("/add")
    public GatewayRouteEntity add(@RequestBody GatewayRouteRequest gateway) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        GatewayRouteEntity gatewayRouteEntity = GatewayRouteRequest.toGatewayRouteEntity(gateway);
        System.out.println("添加接口：{}"+gatewayRouteEntity.toString());
        GatewayRouteEntity save = gatewayDao.save(gatewayRouteEntity);
        gatewayServiceHandler.loadRouteConfig();
        return save;
    }

    @GetMapping("/delete")
    public String deleteRoute(Long id){
        gatewayDao.deleteById(id);
        gatewayServiceHandler.deleteRoute(id.toString());
        return "Success";
    }
}
